<?php
declare (strict_types = 1);

namespace app;

use app\admin\model\AdminLog;
use app\admin\model\Nav;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class AdminBaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    protected $img;
    protected $username;
    protected $uid;
    protected $userimg;
    public $page;
    public $size;
    public $data;
    public $query;

    public $routeArr;//管理所有的路由权限

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;
        //初始化分页数据
        $this->data    = $this->request->param();
        $this->query   = http_build_query($this->data);
        $this->getPageAndSize($this->data);
        // 控制器初始化
        $this->initialize();
    }

    /**
     * 检查是否具有路由权限
     */
    public function checkRoute(){
        $requestRoute="/".$this->request->controller()."/".$this->request->action();
        $nav = new Nav();
        $where[]=["status","=","1"];
        $where[]=["is_del","=","0"];
        $where[]=["id","in",$nav->getRuleIds()];
        $this->routeArr=$routeArr=array_column(getDbAll("nav",$where,"","","nav_url"),"nav_url");
        if(!in_array($requestRoute,$routeArr) && $requestRoute!="/Index/index"){
            header("Location:/Index/index");//redirect("/Index/index");
        }
        assign("routeArr",$routeArr);
    }
    // 初始化
    protected function initialize()
    {
        $user = session('admin');
        if(empty($user))
        {
            $this->success('您还没登录，请返回页面重新登录', 'Login/login');
        }
        $this->img = 'upload/bg/default.png';
        $this->username = $user['username'];
        $this->uid = $user['id'];
        $this->userimg = $user['userimg'];
        $this->checkRoute();//检查是否具有路由权限
        $this->addAdminLog();//添加后台请求日志
    }
    /**
     * 添加后台请求日志
     */
    private function addAdminLog(){
        $adminlog = new AdminLog();
        $content = '';
        if(!empty($this->request->param())){
            $con = $this->request->param();
            $content = json_encode($con);
        }
        $save = array(
            'name' => $this->username,
            'status' => 2,
            'log_name' => @$_SERVER['REDIRECT_URL']?getMenuName(@$_SERVER['REDIRECT_URL']):getMenuName(@$_SERVER['REQUEST_URI']),
            'content' => $content,
            'createtime' => time(),
            'type' => @$_SERVER['REDIRECT_URL']?@$_SERVER['REDIRECT_URL']:@$_SERVER['REQUEST_URI'],
        );
        $adminlog->insert($save);
    }
    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        $v->message($message);
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        return $v->failException(true)->check($data);
    }
    //初始化分页数据
    public function getPageAndSize($data)
    {
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : 10;
    }
    /**
     * @param $tablename
     * @param $save
     * 公用新增方法
     */
    protected function dbSave($tablename,$save){
        $res=Db::name($tablename)->save($save);
        if($res){
            exit(json_encode(["code"=>200,"msg"=>"保存成功！","data"=>[]]));
        }else{
            exit(json_encode(["code"=>400,"msg"=>"保存失败！","data"=>[]]));
        }
    }
    /**
     * @param $tablename
     * @param $save
     * @param $where
     * 公用修改方法
     */
    protected function dbUpdate($tablename,$data,$where){
        $res=Db::name($tablename)->where($where)->update($data);
        if($res){
            exit(json_encode(["code"=>200,"msg"=>"修改成功！","data"=>[]]));
        }else{
            exit(json_encode(["code"=>400,"msg"=>"修改失败！","data"=>[]]));
        }
    }
    /**
     * @param $tablename
     * @param array $where
     * 公用数据库删除
     */
    protected function dbDelete($tablename, $where=[]){
        $res=Db::name($tablename)->where($where)->delete();
        if($res){
            exit(json_encode(["code"=>200,"msg"=>"删除成功！","data"=>[]]));
        }else{
            exit(json_encode(["code"=>400,"msg"=>"删除失败！","data"=>[]]));
        }
    }
    use \liliuwei\think\Jump;
}
